<?PHP

$output = null;
$columns = null;


if(isset($_GET["query"])){
    
  
    $_mysqli = new mysqli('localhost', 'cs143', '', 'CS143');
    
    $result = $_mysqli->query($_GET["query"]);
    
    
    $columns = array();
    while($row = mysqli_fetch_field($result)){
        $columns[] = $row->name;
    }
    
    $output = array();
    while($row = mysqli_fetch_assoc($result)){
        $output[] = $row;
    }
}

?>


<html>
    <head>
        <title>CS143 Project 1B</title>
        <style type="text/css">
            thead{
                font-weight: bold;
            }
        </style>
    </head>
    <body>
        <p> Welcome to the query box.</p>
        <p>
            <form action="query.php" method="GET">
                <p>
                    <textarea name="query" cols="60" rows="8"><?PHP if($_GET['query']) echo $_GET['query']; ?></textarea>
                </p>
                <p><input type="submit" value="Submit" /></p>
                
            </form>
        </p>
        
        
        <?PHP
        
        function printRow($row){
            echo "<tr>";
            foreach($row as $cell){
                echo "<td>$cell</td>";
            }
            echo "</tr>";
        }
        
        if($output){
           echo "<table>";
           
           //Print header section.
           echo "<thead>";

           printRow($columns);

           echo "</thead>";

           //Print output section.
           echo "<tbody>";
           foreach($output as $row){
               printRow($row);
           }
           echo "</tbody>";
           
           echo "</table>";
            
        }
        
        ?>

    </body>
</html>
